package com.dyb.demo.test_thread;

/**
 * 子线程执行10次，主线程执行100次，这样循环50次
 */
public class ThreadTest {

    public static void main(String[] a) {
        final int times = 1;
        final Business business = new Business();

        new Thread(()->{
            for (int i=0; i<times; i++) {
                business.subThread(i);
            }
        }).start();

        for (int i=0; i<times; i++) {
            business.mainThread(i);
        }
    }
}

class Business {

    boolean shouldSub = true;
    public synchronized void mainThread(int i) {
        System.out.println(System.currentTimeMillis() + "============start mainThread");
        if (shouldSub) {
            try {
                Thread.sleep(2000);
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j=0; j<100; j++) {
            System.out.println(System.currentTimeMillis() + ", MainThread: times=" + i + ", j=" + j);
        }
        shouldSub = true;
        this.notify();
    }

    public synchronized void subThread(int i) {
        System.out.println(System.currentTimeMillis() + "============start subThread");
        if (!shouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        for (int j=0; j<10; j++) {
            System.out.println(System.currentTimeMillis() + ", SubThread: times=" + i + ", j=" + j);
        }
        shouldSub = false;
        this.notify();
    }
}